import {defineStore} from 'pinia'
import {ref,computed} from 'vue'
import {addAddressAPI, delAddressAPI, getAddressListAPI} from "@/apis/address.js";
import {useUserStore} from "@/stores/user.js";


export const useAddressStore = defineStore('addressList', () => {
    const addressList = ref([])

    //装载收货地址列表
    const loadAddressList=(list)=>{
        addressList.value=list
    }

    //添加收货地址
    const addAddress=(address)=>{
        addressList.value.push(address)
        //如果当前只有一个地址，则设为默认地址
        if(addressList.value.length===1){
            addressList.value[0].isDefault=1
        }
    }
    //清除收货地址
    const clearAddressList=()=>{
        addressList.value=[]
    }

    //修改地址
    const alterAddress=(index,newAddress)=>{
        addressList.value[index]=newAddress
    }

    //删除地址
    const delAddress=(index)=>{
        addressList.value.splice(index,1)
    }

    //设为默认地址
    const setDefault=(setIndex)=>{
        addressList.value.forEach((item,index)=>{
            if (index===setIndex){
                item.isDefault=1
            }else{
                item.isDefault=0
            }
        })
    }

    const isEmpty=computed(()=>{
        return !addressList.value || addressList.value.length===0
    })

        return {
            addressList,
            loadAddressList,
            delAddress,
            alterAddress,
            addAddress,
            setDefault,
            isEmpty,
            clearAddressList
    }
    },
    {
        //持久化存储
        persist: true,
    }
)
